package com.ai.service.impl;

import com.ai.entity.SysRolePermissionEntity;
import com.ai.mapper.SysRolePermissionMapper;
import com.ai.service.RolePermissionService;
import com.ai.web.request.RolePermissionReq;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限关联
 */
@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Resource
    SysRolePermissionMapper sysRolePermissionMapper;

    @Transactional
    @Override
    public void addRolePermission(RolePermissionReq vo) {
        sysRolePermissionMapper.delete(Wrappers.<SysRolePermissionEntity>lambdaQuery().eq(SysRolePermissionEntity::getRoleId, vo.getRoleId()));
        vo.getPermissionIds().forEach(e -> {
            SysRolePermissionEntity sysRolePermission = new SysRolePermissionEntity();
            sysRolePermission.setRoleId(vo.getRoleId());
            sysRolePermission.setPermissionId(e);
            sysRolePermissionMapper.insert(sysRolePermission);
        });
    }


    @Override
    public List<String> getPermissionIds(List<String> roleIds) {
        List<SysRolePermissionEntity> sysRolePermissions = sysRolePermissionMapper.selectList(Wrappers.<SysRolePermissionEntity>lambdaQuery().in(SysRolePermissionEntity::getRoleId, roleIds));
        return sysRolePermissions.stream().map(SysRolePermissionEntity::getPermissionId).collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleIds(String permissionId) {
        List<SysRolePermissionEntity> sysRolePermissions = sysRolePermissionMapper.selectList(Wrappers.<SysRolePermissionEntity>lambdaQuery().eq(SysRolePermissionEntity::getPermissionId, permissionId));
        return sysRolePermissions.stream().map(SysRolePermissionEntity::getRoleId).collect(Collectors.toList());
    }

}
